App({
  globalData: {
    userInfo: null,
    shopInfo: {
      name: '',
      logo: '',
      description: ''
    },
    shopStatus: 'closed', // 'open' 出摊中, 'rest' 休息中, 'closed' 已关闭
    todayVisitors: 0,
    todayFans: 0,
    location: {
      latitude: 0,
      longitude: 0,
      name: '',
      address: ''
    },
    token: '', // 用户登录凭证
    isLogin: false,
    hasShop: false, // 是否有摊位
    isVerified: false, // 是否已实名认证
    products: [], // 商品列表缓存
    // 开发模式标志，开启时使用模拟数据代替API调用
    devMode: true
  },
  onLaunch: function() {
    // 初始化应用时直接尝试自动登录
    this.checkLoginStatus();
  },
  
  // 封装请求方法，支持开发模式下的模拟数据
  request: function(options) {
    // 开发模式下，返回模拟数据
    if (this.globalData.devMode) {
      return this.mockRequest(options);
    }
    
    // 正常模式，使用封装的request模块发起请求
    const requestModule = require('./utils/request');
    return requestModule.request(options);
  },
  
  // 模拟API请求
  mockRequest: function(options) {
    console.log('模拟请求:', options.url, options.data || {});
    
    let response = null;
    const url = options.url;
    
    // 模拟不同接口的返回数据
    if (url.includes('/auth/verify')) {
      // 模拟token验证接口
      response = {
        data: {
          valid: true,
          message: '有效token'
        }
      };
    } else if (url.includes('/auth/wxlogin')) {
      // 模拟微信登录接口
      response = {
        data: {
          token: 'mock_token_' + Date.now(),
          userInfo: {
            nickName: '测试用户',
            avatarUrl: '/images/tabbar/business.png'
          }
        }
      };
    } else if (url.includes('/shop/info')) {
      // 模拟店铺信息接口
      if (this.globalData.hasShop) {
        response = {
          data: {
            shop: {
              name: '测试摊位',
              logo: '/images/tabbar/business_active.png',
              description: '这是一个测试摊位'
            }
          }
        };
      } else {
        response = {
          data: {
            shop: null,
            message: '未找到店铺信息'
          }
        };
      }
    } else if (url.includes('/shop/status')) {
      // 模拟更新店铺状态接口
      response = {
        data: {
          success: true,
          message: '状态更新成功'
        }
      };
    } else if (url.includes('/shop/location')) {
      // 模拟更新店铺位置接口
      response = {
        data: {
          success: true,
          message: '位置更新成功'
        }
      };
    } else if (url.includes('/shop/create')) {
      // 模拟创建店铺接口
      this.globalData.hasShop = true;
      this.globalData.shopInfo = options.data || {};
      response = {
        data: {
          success: true,
          message: '创建成功',
          shop: options.data
        }
      };
    } else if (url.includes('/shop/statistics')) {
      // 模拟统计数据接口
      response = {
        data: {
          statistics: {
            todayVisits: 50,
            todayIncome: 300.5,
            weekVisits: 320,
            weekIncome: 2100.8
          }
        }
      };
    } else if (url.includes('/user/verify')) {
      // 模拟实名认证接口
      this.globalData.isVerified = true;
      response = {
        data: {
          success: true,
          message: '认证成功'
        }
      };
    } else if (url.includes('/user/verification/status')) {
      // 模拟获取认证状态接口
      response = {
        data: {
          verified: this.globalData.isVerified,
          message: this.globalData.isVerified ? '已认证' : '未认证'
        }
      };
    } else {
      // 默认返回
      response = {
        data: {
          success: true,
          message: '模拟请求成功'
        }
      };
    }
    
    // 模拟异步响应
    setTimeout(() => {
      if (options.success) {
        options.success(response);
      }
    }, 500);
    
    // 返回request对象以兼容wx.request的返回值
    return {
      abort: function() {
        console.log('请求被终止');
      }
    };
  },
  
  checkLoginStatus: function() {
    // 检查登录状态
    const token = wx.getStorageSync('token');
    if (token) {
      // 验证token是否有效
      if (this.globalData.devMode) {
        // 开发模式下使用模拟数据
        this.request({
          url: 'https://api.example.com/auth/verify',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data && res.data.valid) {
              this.globalData.isLogin = true;
              this.globalData.token = token;
              this.globalData.userInfo = wx.getStorageSync('userInfo');
              
              // 登录成功后获取店铺信息
              this.getShopInfo();
              // 获取认证状态
              this.getVerificationStatus();
              // 获取位置信息
              this.getLocation();
            } else {
              // token无效，需要重新登录
              this.autoLogin();
            }
          },
          fail: () => {
            this.autoLogin();
          }
        });
      } else {
        // 正常模式下使用API模块
        const api = require('./services/index');
        api.auth.verifyToken().then(data => {
          if (data && data.valid) {
            this.globalData.isLogin = true;
            this.globalData.token = token;
            this.globalData.userInfo = wx.getStorageSync('userInfo');
            
            // 登录成功后获取店铺信息
            this.getShopInfo();
            // 获取认证状态
            this.getVerificationStatus();
            // 获取位置信息
            this.getLocation();
          } else {
            // token无效，需要重新登录
            this.autoLogin();
          }
        }).catch(() => {
          this.autoLogin();
        });
      }
    } else {
      // 没有token，尝试自动登录
      this.autoLogin();
    }
  },
  
  // 获取认证状态
  getVerificationStatus: function() {
    if (!this.globalData.token) return;
    
    if (this.globalData.devMode) {
      // 开发模式下使用模拟数据
      this.request({
        url: 'https://api.example.com/user/verification/status',
        header: {
          'Authorization': `Bearer ${this.globalData.token}`
        },
        success: (res) => {
          if (res.data && res.data.verified !== undefined) {
            this.globalData.isVerified = res.data.verified;
          }
        }
      });
    } else {
      // 正常模式下使用API模块
      const api = require('./services/index');
      api.user.getVerificationStatus().then(data => {
        if (data && data.verified !== undefined) {
          this.globalData.isVerified = data.verified;
        }
      }).catch(err => {
        console.error('获取认证状态失败:', err);
      });
    }
  },
  
  // 自动登录（微信授权登录）
  autoLogin: function() {
    wx.login({
      success: (res) => {
        if (res.code) {
          if (this.globalData.devMode) {
            // 开发模式下使用模拟数据
            this.request({
              url: 'https://api.example.com/auth/wxlogin',
              method: 'POST',
              data: {
                code: res.code
              },
              success: (loginRes) => {
                if (loginRes.data && loginRes.data.token) {
                  const token = loginRes.data.token;
                  const userInfo = loginRes.data.userInfo || {};
                  
                  wx.setStorageSync('token', token);
                  wx.setStorageSync('userInfo', userInfo);
                  
                  this.globalData.isLogin = true;
                  this.globalData.token = token;
                  this.globalData.userInfo = userInfo;
                  
                  // 登录成功后获取店铺信息
                  this.getShopInfo();
                  // 获取认证状态
                  this.getVerificationStatus();
                  // 获取位置信息
                  this.getLocation();
                } else {
                  // 静默登录失败，需要用户主动授权
                  this.redirectToLogin();
                }
              },
              fail: () => {
                this.redirectToLogin();
              }
            });
          } else {
            // 正常模式下使用API模块
            const api = require('./services/index');
            api.auth.wxLogin(res.code).then(data => {
              if (data && data.token) {
                const token = data.token;
                const userInfo = data.userInfo || {};
                
                wx.setStorageSync('token', token);
                wx.setStorageSync('userInfo', userInfo);
                
                this.globalData.isLogin = true;
                this.globalData.token = token;
                this.globalData.userInfo = userInfo;
                
                // 登录成功后获取店铺信息
                this.getShopInfo();
                // 获取认证状态
                this.getVerificationStatus();
                // 获取位置信息
                this.getLocation();
              } else {
                // 静默登录失败，需要用户主动授权
                this.redirectToLogin();
              }
            }).catch(() => {
              this.redirectToLogin();
            });
          }
        } else {
          this.redirectToLogin();
        }
      },
      fail: () => {
        this.redirectToLogin();
      }
    });
  },
  
  // 重定向到登录页
  redirectToLogin: function() {
    this.globalData.isLogin = false;
    this.globalData.token = '';
    this.globalData.userInfo = null;
    
    wx.redirectTo({
      url: '/pages/login/login'
    });
  },
  
  // 登录方法，供页面调用
  login: function(callback) {
    if (this.globalData.devMode) {
      // 开发模式下使用模拟登录
      this.autoLogin();
      if (typeof callback === 'function') {
        setTimeout(() => {
          callback(true);
        }, 500);
      }
    } else {
      // 正常模式下使用微信登录
      wx.login({
        success: (res) => {
          if (res.code) {
            const api = require('./services/index');
            api.auth.wxLogin(res.code).then(data => {
              if (data && data.token) {
                const token = data.token;
                const userInfo = data.userInfo || {};
                
                wx.setStorageSync('token', token);
                wx.setStorageSync('userInfo', userInfo);
                
                this.globalData.isLogin = true;
                this.globalData.token = token;
                this.globalData.userInfo = userInfo;
                
                // 登录成功后获取店铺信息
                this.getShopInfo();
                // 获取认证状态
                this.getVerificationStatus();
                // 获取位置信息
                this.getLocation();
                
                if (typeof callback === 'function') {
                  callback(true);
                }
              } else {
                if (typeof callback === 'function') {
                  callback(false);
                }
              }
            }).catch(err => {
              console.error('登录失败:', err);
              if (typeof callback === 'function') {
                callback(false);
              }
            });
          } else {
            if (typeof callback === 'function') {
              callback(false);
            }
          }
        },
        fail: () => {
          if (typeof callback === 'function') {
            callback(false);
          }
        }
      });
    }
  },
  
  // 获取店铺信息
  getShopInfo: function() {
    if (!this.globalData.token) return;
    
    if (this.globalData.devMode) {
      // 开发模式下使用模拟数据
      this.request({
        url: 'https://api.example.com/shop/info',
        header: {
          'Authorization': `Bearer ${this.globalData.token}`
        },
        success: (res) => {
          if (res.data && res.data.shop) {
            this.globalData.shopInfo = res.data.shop;
            this.globalData.hasShop = true;
            
            // 有店铺信息，进入首页
            if (getCurrentPages().length === 0) {
              wx.switchTab({
                url: '/pages/index/index'
              });
            }
          } else {
            // 用户没有店铺信息，需要创建
            this.globalData.hasShop = false;
            
            // 重定向到创建店铺页面
            if (getCurrentPages().length === 0) {
              wx.redirectTo({
                url: '/pages/shop/create/create'
              });
            }
          }
        },
        fail: () => {
          // 请求失败，默认为没有店铺
          this.globalData.hasShop = false;
        }
      });
    } else {
      // 正常模式下使用API模块
      const api = require('./services/index');
      api.shop.getShopInfo().then(data => {
        if (data && data.shop) {
          this.globalData.shopInfo = data.shop;
          this.globalData.hasShop = true;
          
          // 有店铺信息，进入首页
          if (getCurrentPages().length === 0) {
            wx.switchTab({
              url: '/pages/index/index'
            });
          }
        } else {
          // 用户没有店铺信息，需要创建
          this.globalData.hasShop = false;
          
          // 重定向到创建店铺页面
          if (getCurrentPages().length === 0) {
            wx.redirectTo({
              url: '/pages/shop/create/create'
            });
          }
        }
      }).catch(err => {
        console.error('获取店铺信息失败:', err);
        // 请求失败，默认为没有店铺
        this.globalData.hasShop = false;
      });
    }
  },
  
  // 登录方法已在上面定义，此处删除重复的定义
  
  logout: function() {
    this.globalData.isLogin = false;
    this.globalData.token = '';
    this.globalData.userInfo = null;
    this.globalData.shopInfo = {
      name: '',
      logo: '',
      description: ''
    };
    this.globalData.hasShop = false;
    this.globalData.isVerified = false;
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
    // 跳转到登录页
    wx.reLaunch({
      url: '/pages/login/login'
    });
  },
  
  getLocation: function() {
    // 获取位置信息
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.globalData.location.latitude = res.latitude;
        this.globalData.location.longitude = res.longitude;
        
        // 在开发模式下，模拟位置信息
        if (this.globalData.devMode) {
          const mockLocation = {
            name: '示例区示例街道',
            address: '示例省示例市示例区示例街道示例大厦'
          };
          
          this.globalData.location.name = mockLocation.name;
          this.globalData.location.address = mockLocation.address;
          
          // 模拟上传位置信息到服务器
          console.log('模拟上传位置信息:', this.globalData.location);
        } else {
          // 根据经纬度获取位置详细信息
          wx.request({
            url: `https://api.map.baidu.com/reverse_geocoding/v3/?ak=YOUR_BAIDU_MAP_KEY&output=json&coordtype=gcj02ll&location=${res.latitude},${res.longitude}`,
            success: (locationRes) => {
              if (locationRes.data && locationRes.data.result) {
                const result = locationRes.data.result;
                this.globalData.location.name = result.addressComponent.district + result.addressComponent.street;
                this.globalData.location.address = result.formatted_address;
                
                // 将位置信息上传到服务器
                if (this.globalData.isLogin && this.globalData.token) {
                  this.request({
                    url: 'https://api.example.com/shop/location',
                    method: 'POST',
                    header: {
                      'Authorization': `Bearer ${this.globalData.token}`
                    },
                    data: {
                      latitude: res.latitude,
                      longitude: res.longitude,
                      name: this.globalData.location.name,
                      address: this.globalData.location.address
                    }
                  });
                }
              }
            }
          });
        }
      },
      fail: (err) => {
        console.error('获取位置失败', err);
        // 如果用户拒绝授权，引导用户开启位置权限
        if (err.errMsg.indexOf('auth deny') >= 0) {
          wx.showModal({
            title: '提示',
            content: '需要获取您的地理位置，请确认授权',
            success: (res) => {
              if (res.confirm) {
                // 打开设置页面
                wx.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting['scope.userLocation']) {
                      // 用户已授权，重新获取位置
                      this.getLocation();
                    }
                  }
                });
              }
            }
          });
        }
      }
    });
  },
  
  updateShopStatus: function(status, callback) {
    // 如果要设置为营业中，需要先检查是否已认证
    if (status === 'open' && !this.globalData.isVerified) {
      wx.showModal({
        title: '实名认证',
        content: '开始营业前需要完成实名认证',
        confirmText: '去认证',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/verification/verification'
            });
          }
        }
      });
      if (callback) callback(false, '需要先完成实名认证');
      return;
    }
    
    // 更新店铺状态
    this.globalData.shopStatus = status;
    // 调用API更新服务器状态
    if (this.globalData.token) {
      this.request({
        url: 'https://api.example.com/shop/status',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${this.globalData.token}`
        },
        data: {
          status: status
        },
        success: (res) => {
          if (callback) callback(true);
        },
        fail: () => {
          if (callback) callback(false);
        }
      });
    } else {
      if (callback) callback(false);
    }
  }
})